import { useState, useEffect, useCallback, useImperativeHandle } from 'react'
// ===================================================================== 
// ===================================================================== Data
const tabs = ['实验室', '测试组', '仪器']
const { $http, $Lazy } = window
// ===================================================================== Lazy
const FoldItem 			= $Lazy.load(()=>import('./cpt/fold-item'))

const Index = ({thisRef}, ref) => {
	const [active, setActive] = useState(0)
	const [data, setData] = useState([])
	const [key, setkey] = useState(0)
	const onClick = i => {
		setActive(i)
		const listType = i === 0 ? 'lot' : i === 1 ? 'group' : 'device'
		thisRef.cRow = {}
		thisRef.pRow = { type: listType }
		thisRef.headerRef.setState({})
	}
	
	const fetch = type => $http.pull(null, 'qc-test/list', {param: {type}}).then(data => setData(data))
	
	useEffect(() => {
		fetch(active === 0 ? 'lot' : active === 1 ? 'group' : 'device')
	}, [active])
	
	const change = useCallback((type, value) => {
		const listType = active === 0 ? 'lot' : active === 1 ? 'group' : 'device'
		if (type) {
			thisRef.cRow = value
			thisRef.pRow = { type: listType }
		} else {
			thisRef.cRow = {}
			thisRef.pRow = {...value, type: listType }
		}
		thisRef.type = type
		thisRef.listType = listType
		setkey(key + 1)
		thisRef.headerRef.setState({})
	}, [key, thisRef, active])
	
	useImperativeHandle(ref, () => ({
		update: () => setkey(key + 1),
		fetch: () => fetch(active === 0 ? 'lot' : active === 1 ? 'group' : 'device')
	}))
	
	return <div style={{width: '20%'}} className='fv bcf r5px oys scrollbar'>
		<div className='fxm'>
			{ tabs.map((v, i) => <div key={i} className='fv xm ptb10 ml15 mr15 r5px cp' onClick={() => onClick(i)}>
				<span className={active === i ? 'tab' : ''}>{v}</span>
			</div>) }
		</div>
		<div className='ex oxys scrollbar'>
			<div className='plr10'>
				{ data.map(v => <FoldItem data={v} key={v.id} onChange={change} thisRef={thisRef} />) }
			</div>
		</div>
	</div>
} 

export default Index